package com.snail.common.dyd.impl;

import cn.hutool.core.util.StrUtil;
import com.snail.common.dyd.DataBaseOperator;
import com.snail.common.dyd.DataBaseOperatorProvider;
import com.snail.common.dyd.DataBaseTypeRep;
import com.snail.common.dyd.bean.DataBaseType;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;

import java.util.Map;

@Slf4j
public class DefaultDataBaseOperatorProvider implements DataBaseOperatorProvider {

    @Setter
    @Getter
    private String  dataBaseOperatorBeanNamePrefix = "databaseOperatorOf";

    private ApplicationContext context;

    public DefaultDataBaseOperatorProvider(ApplicationContext context) {
        this.context = context;
    }


    @Override
    public DataBaseOperator getDataBaseOperator(Integer dataBaseTypeCode) {
        DataBaseType dataBaseType = DataBaseTypeRep.getDataBaseType(dataBaseTypeCode);
        if(dataBaseType == null){
            log.error("未找到对应的数据库类型, code: {}", dataBaseTypeCode);
            return null;
        }
        String dataBaseTypeId = dataBaseType.getTypeId();
        // 6.根据别名获取对应的mapper的实现.
        Map<String, DataBaseOperator> dataBaseOperatorMap = context.getBeansOfType(DataBaseOperator.class);
        return dataBaseOperatorMap.values()
                .stream()
                .filter(dataBaseOperator -> dataBaseOperator.getDataBaseType().equals(dataBaseTypeId))
                .findFirst()
                .orElse(null);
    }
}
